<template>
  <a-modal
    v-model:open="open"
    :title="modalTitle"
    :confirm-loading="confirmLoading"
    @ok="onOk"
    @cancel="onCancel"
    destroy-on-close
  >
    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item
        name="categoryImgUrl"
        :wrapper-col="{ span: 24 }"
        style="text-align: center"
      >
        <div flex justify-center>
          <a-upload
            v-model:file-list="fileList"
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader w-auto!"
            :show-upload-list="false"
            action=""
            :before-upload="file => beforeUpload(file, 'category')"
            :customRequest="file => uploadImage(file, 'category')"
            @change="onCategoryImgUrlChange"
          >
            <img
              v-if="formState.categoryImgUrl"
              :src="formState.categoryImgUrl"
              alt="avatar"
              style="object-fit: scale-down"
              w-100px
              h-100px
            />
            <div v-else>
              <plus-outlined></plus-outlined>
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-upload
            v-model:file-list="logoFileList"
            name="avatar"
            list-type="picture-card"
            class="w-auto!"
            :show-upload-list="false"
            action=""
            :before-upload="file => beforeUpload(file, 'icon')"
            :customRequest="file => uploadImage(file, 'icon')"
            @change="onCategoryImgUrlChange"
          >
            <img
              v-if="formState.logoUrl"
              :src="formState.logoUrl"
              alt="avatar"
              style="object-fit: scale-down"
              w-100px
              h-100px
            />
            <div v-else>
              <plus-outlined></plus-outlined>
              <div class="ant-upload-text">上传icon</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <a-form-item
        v-if="categoryType === 'LEAF'"
        label="类目代码"
        name="categoryCode"
        :rules="[{ required: true, message: '请填写类目代码' }]"
      >
        <a-input
          v-model:value="formState.categoryCode"
          :disabled="formType == 'edit'"
          :maxlength="20"
        />
      </a-form-item>

      <a-form-item label="数据来源" v-if="categoryType == 'LEAF'">
        <a-radio-group
          v-model:value="formState.alignMode"
          :disabled="formType == 'edit'"
        >
          <a-radio value="MERGER">合并模式</a-radio>
          <a-radio value="CUSTOM">合并/自建</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        :label="categoryType === 'LEAF' ? '类目名称' : '分类名称'"
        name="categoryName"
        :rules="[{ required: true, message: '请填写类目名称' }]"
      >
        <a-input v-model:value="formState.categoryName" :maxlength="20" />
      </a-form-item>

      <a-form-item
        v-if="categoryType === 'LEAF'"
        label="描述"
        name="categoryDesc"
      >
        <a-textarea v-model:value="formState.categoryDesc" :maxlength="200"
          >描述</a-textarea
        >
      </a-form-item>

      <a-form-item
        label="上级分类"
        name="parentId"
        :rules="[{ required: true, message: '请选择上级分类' }]"
      >
        <a-tree-select
          v-model:value="formState.parentId"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :fieldNames="{
            children: 'children',
            label: 'categoryName',
            value: 'id',
          }"
          placeholder="请选择"
          allow-clear
          tree-default-expand-all
          :tree-data="selectableParentTree"
        >
        </a-tree-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { onMounted, ref, reactive, computed } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/api/global';
import { createCategory, editCategory } from '@/api/hc_category';
import { breadFirstTree } from '@/utils/util';
import { message } from 'ant-design-vue';

const props = defineProps({
  parentTree: {
    type: Array,
    required: true,
  },
});

const fileList = ref([]);
const logoFileList = ref([]);
const formRef = ref(null);

const open = ref(false);
const categoryId = ref();
const formState = reactive({
  categoryCode: '',
  categoryName: '',
  categoryDesc: '',
  parentId: '',
  logoUrl: '',
  alignMode: 'MERGER',
});

const categoryType = ref('TRUNK'); // 分类-TRUNK，类目-LEAF
const formType = ref('create'); // 新建-create，编辑-edit

const confirmLoading = ref(false);

const treeData = ref([]);

const emit = defineEmits(['ok']);

const modalTitle = computed(() => {
  if (categoryType.value === 'TRUNK') {
    if (formType.value === 'create') {
      return '新建分类';
    } else {
      return '编辑分类';
    }
  } else {
    if (formType.value === 'create') {
      return '新增类目';
    } else {
      return '编辑类目';
    }
  }
});

const selectableParentTree = computed(() => {
  const tree = props.parentTree;
  if (formType.value === 'edit') {
    breadFirstTree(
      tree,
      node => {
        if (formType.value === 'edit') {
          node.children = node.children.filter(
            ele => ele.id !== categoryId.value,
          );
        }
        return true;
      },
      'children',
    );
  }
  return tree;
});

const onNew = (parentId, type) => {
  categoryType.value = type;
  formState.parentId = parentId;
  open.value = true;
  formType.value = 'create';
};

const onEdit = (data, type) => {
  categoryType.value = type;
  const {
    id,
    categoryCode,
    categoryImgUrl,
    categoryName,
    categoryDesc,
    parentId,
    logoUrl,
    alignMode,
  } = data;
  categoryId.value = id;
  formState.categoryCode = categoryCode;
  formState.categoryName = categoryName;
  formState.categoryDesc = categoryDesc;
  formState.categoryImgUrl = categoryImgUrl;
  formState.parentId = parentId;
  formState.logoUrl = logoUrl;
  formState.alignMode = alignMode;
  open.value = true;
  formType.value = 'edit';
};

const beforeUpload = (file, type) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isSvg = file.type === 'image/svg';
  if (type == 'category') {
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG文件!');
      return false;
    }
  } else if (type === 'icon') {
    if (!isJpgOrPng && !isSvg) {
      message.error('只能上传JPG/PNG/SVG文件!');
      return false;
    }
  }

  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }
  return isLt2M;
};

const uploadImage = (data, type) => {
  uploadFile(data.file, 'CategoryLogo').then(res => {
    if (res.code === 'ok') {
      if (type == 'category') {
        formState.categoryImgUrl = res.data;
      } else if (type == 'icon') {
        formState.logoUrl = res.data;
      }
    }
  });
};

const onCategoryImgUrlChange = info => {};

const onOk = () => {
  formRef.value
    .validate()
    .then(() => {
      const data = {
        parentId: formState.parentId,
        categoryCode: formState.categoryCode,
        categoryName: formState.categoryName,
        categoryDesc: formState.categoryDesc,
        categoryImgUrl: formState.categoryImgUrl,
        alignMode: formState.alignMode,
        type: categoryType.value,
        logoUrl: formState.logoUrl,
      };
      if (formType.value === 'create') {
        confirmLoading.value = true;
        createCategory(data)
          .then(res => {
            if (res.code === 'ok') {
              emit('ok');
              onCancel();
            } else {
              // message.error(res.message);
            }
          })
          .catch(error => {
            console.log('error', error);
            // message.error(error.message);
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      } else if (formType.value === 'edit') {
        data.id = categoryId.value;
        confirmLoading.value = true;
        editCategory(data)
          .then(res => {
            if (res.code === 'ok') {
              emit('ok', data);
              onCancel();
            } else {
              // message.error(res.message);
            }
          })
          .catch(error => {
            console.log('error', error);
            // message.error(error.message);
          })
          .finally(() => {
            confirmLoading.value = false;
          });
      } else return;
    })
    .catch(error => {
      console.log('error', error);
    });
};

const onCancel = () => {
  resetForm();
  open.value = false;
};

const resetForm = () => {
  formRef.value.resetFields();
  formState.logoUrl = '';
  formState.categoryCode = '';
  formState.categoryName = '';
  formState.categoryDesc = '';
  formState.categoryImgUrl = '';
  formState.parentId = '';
};

defineExpose({
  onNew,
  onEdit,
});
</script>

<script>
import {
  Form,
  Modal,
  FormItem,
  Input,
  TreeSelect,
  Textarea,
  Upload,
} from 'ant-design-vue';
export default {
  components: {
    AForm: Form,
    AModal: Modal,
    AFormItem: FormItem,
    AInput: Input,
    ATreeSelect: TreeSelect,
    ATextarea: Textarea,
    AUpload: Upload,
  },
};
</script>

<style lang="scss" scoped></style>
